
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-01
 * Time: 22:17
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 * 二叉树转字符串
 * 考虑四种情况
 * left==null  right==null
 * left==null  right!=null
 * left!=null  right==null
 * left!=null  right!=null
 */
public class Solution {
    public void treeToStr(TreeNode root,StringBuilder sb){
        if(root==null){
            return;
        }
        sb.append(root.val);
        if(root.left!=null){
            //左树不为空
            sb.append("(");
            treeToStr(root.left,sb);
            //左树递归完了再加)
            sb.append(")");
        }else{
            //左树为空
            if(root.right!=null){
                //左树为空右树不为空加上()
                sb.append("()");
            }else{
                //为空直接return回去之后会加括号
                return;
            }
        }

        if(root.right!=null){
            //右树不为空
            sb.append("(");
            treeToStr(root.right,sb);
            //右树递归完了再加)
            sb.append(")");
        }else{
            //为空直接return回去之后会加括号
            return ;
        }
    }
    public String tree2str(TreeNode root) {
        StringBuilder sb=new StringBuilder();
        treeToStr(root,sb);
        return sb.toString();
    }
}
